//
//  BaseTextField.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/26.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
@objc protocol BaseTextFieldDelegate: class {
    
    /// textField变动
    ///
    /// - Parameter textField: textField
    @objc optional func textFieldDidChange(textField:BaseTextField)
}

class BaseTextField: UITextField {
    var szBounds:CGRect?
    var offest:CGFloat = 0.00
    var changeView:UIView?
    weak var textDelegate:BaseTextFieldDelegate?
    init(changeView:UIView?,szBounds:CGRect) {
        super.init(frame: CGRect.zero)
        self.szBounds = szBounds
        self.changeView = changeView
        self.themeTextColor = ThemeManager.ThemeColorKeys.text1
        NotificationCenter.default.addObserver(self, selector: #selector(notifierKeyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(notifierKeyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        self.setValue(UIFont.systemFont(ofSize: 15), forKeyPath: "_placeholderLabel.font")
        self.delegate = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(textFiledDidChanged(notification:)), name: NSNotification.Name.UITextFieldTextDidChange, object: nil)

        
        self.inputAccessoryView = self.generateToolbar()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func generateToolbar() -> UIToolbar {
        let toolbar =  UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: kSCREEN_WIDTH, height: 44.0))
        let itme1 = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.flexibleSpace , target: nil, action: nil)
        let item2 = UIBarButtonItem(title: kText("完成"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(doneButtonDidPressed))
        toolbar.setItems([itme1, item2], animated: false)
        return toolbar
    }
    
    @objc func doneButtonDidPressed() -> Void {
        self .resignFirstResponder()
    }
    
    override func textRect(forBounds bounds: CGRect) -> CGRect {
        if self.szBounds == CGRect.zero || self.szBounds == nil {
            return CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height)
        }
        return CGRect(x: (self.szBounds?.origin.x)!, y: (self.szBounds?.origin.y)!, width: bounds.size.width-(self.szBounds?.origin.x)!, height: bounds.size.height-(self.szBounds?.origin.y)!)
    }
    
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        if self.szBounds == CGRect.zero || self.szBounds == nil {
            return CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height)
        }
        return CGRect(x: (self.szBounds?.origin.x)!, y: (self.szBounds?.origin.y)!, width: bounds.size.width-(self.szBounds?.origin.x)!, height: bounds.size.height-(self.szBounds?.origin.y)!)
    }
    
    
    @objc func notifierKeyboardWillShow(notification:NSNotification) {
        let firstResponder = UIResponder.firstResponder()
        if firstResponder == nil {
            return
        }
        if !(firstResponder?.isEqual(self))! {
            return
        }
        var subview:UIView;
        let name:AnyObject = object_getClass(self.superview)!
        if String(describing:name) == "UITableViewCellContentView" {
            var tableView:UITableView
            if self.superview?.superview?.superview == nil {
                return
            }
            subview = (self.superview?.superview?.superview)!
            if !subview.isKind(of: UITableView.self) {
                if subview.superview  == nil {
                    return
                }
                tableView = subview.superview as! UITableView
            }else {
                tableView = subview as! UITableView
            }
            
            let screenFrame = tableView.superview?.convert(tableView.frame, to: UIApplication.shared.keyWindow)
            let tableViewBottomOnScreen = (screenFrame?.origin.y)! + (screenFrame?.size.height)!
            let   tableViewGap                 = kSCREEN_HEIGHT - tableViewBottomOnScreen;
            
            let userInfo = notification.userInfo as NSDictionary?
            
            let aValue = userInfo?.object(forKey: UIKeyboardFrameEndUserInfoKey)
            
            let keyboardSize = (aValue as AnyObject).cgRectValue
            var contentInsets  = tableView.contentInset
            contentInsets.bottom  = (keyboardSize?.height)! - tableViewGap
            
            let animationDuration =  (userInfo?.object(forKey: UIKeyboardAnimationDurationUserInfoKey) as! NSNumber).doubleValue
            
            let animationCurve = (userInfo?.object(forKey: UIKeyboardAnimationCurveUserInfoKey) as! NSNumber).intValue
            
            UIView.animateKeyframes(withDuration: animationDuration, delay: 0, options: UIViewKeyframeAnimationOptions(rawValue: UIViewKeyframeAnimationOptions.RawValue(animationCurve)), animations: {
                tableView.contentInset          = contentInsets;
                tableView.scrollIndicatorInsets = contentInsets;
            }) { (make) in
                
            }
            
        }else {
            if self.changeView == nil {
                return;
            }
            
            let userInfo = notification.userInfo as NSDictionary?
            
            let aValue = userInfo?.object(forKey: UIKeyboardFrameEndUserInfoKey)
            
            let keyboardSize = (aValue as AnyObject).cgRectValue
            
            let animationDuration =  (userInfo?.object(forKey: UIKeyboardAnimationDurationUserInfoKey) as! NSNumber).doubleValue
            
            let animationCurve = (userInfo?.object(forKey: UIKeyboardAnimationCurveUserInfoKey) as! NSNumber).intValue
       
            let oldfame = self.convert(self.bounds, to: UIApplication.shared.keyWindow)
            let height = kSCREEN_HEIGHT - (oldfame.size.height) - (oldfame.origin.y) - (keyboardSize?.size.height)!-15
            
            if height < 0 {
                offest = height + offest
                UIView.animateKeyframes(withDuration: animationDuration, delay: 0, options: UIViewKeyframeAnimationOptions(rawValue: UIViewKeyframeAnimationOptions.RawValue(animationCurve)), animations: {
                    self.changeView?.frame =  CGRect(x: (self.changeView?.frame.origin.x)!, y: (self.changeView?.frame.origin.y)! + (height), width: (self.changeView?.frame.size.width)!, height: (self.changeView?.frame.size.height)!)
                    
                }) { (make) in
                    
                }
                
            }
        }
    }
    
    
    @objc func notifierKeyboardWillHide(notification:NSNotification) {
        let userInfo = notification.userInfo as NSDictionary?
        let animationDuration =  (userInfo?.object(forKey: UIKeyboardAnimationDurationUserInfoKey) as! NSNumber).doubleValue
        
        let animationCurve = (userInfo?.object(forKey: UIKeyboardAnimationCurveUserInfoKey) as! NSNumber).intValue
        
        var subview:UIView;
        let name:AnyObject = object_getClass(self.superview) != nil ? object_getClass(self.superview)! : "" as AnyObject
        if String(describing:name) == "UITableViewCellContentView" {
            var tableView:UITableView
            if self.superview?.superview?.superview == nil {
                return
            }
            subview = (self.superview?.superview?.superview)!
            if !subview.isKind(of: UITableView.self) {
                if subview.superview  == nil {
                    return
                }
                tableView = subview.superview as! UITableView
            }else {
                tableView = subview as! UITableView
            }
            
            UIView.animateKeyframes(withDuration: animationDuration, delay: 0, options: UIViewKeyframeAnimationOptions(rawValue: UIViewKeyframeAnimationOptions.RawValue(animationCurve)), animations: {
                tableView.contentInset          = UIEdgeInsets.zero;
                tableView.scrollIndicatorInsets = UIEdgeInsets.zero;
            }) { (make) in
                
            }
        
        }else {
            if self.changeView == nil {
                return;
            }
            UIView.animateKeyframes(withDuration: animationDuration, delay: 0, options: UIViewKeyframeAnimationOptions(rawValue: UIViewKeyframeAnimationOptions.RawValue(animationCurve)), animations: {
                self.changeView?.frame =  CGRect(x: (self.changeView?.frame.origin.x)!, y: (self.changeView?.frame.origin.y)! - self.offest, width: (self.changeView?.frame.size.width)!, height: (self.changeView?.frame.size.height)!)
                
            }) { (make) in
                self.offest = 0.00
            }
            
        }
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
extension BaseTextField:UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == " " {
            return false
        }
        return true
    }
    
    
   @objc func textFiledDidChanged(notification:NSNotification) {
    if textDelegate != nil && textDelegate?.textFieldDidChange != nil {
        textDelegate?.textFieldDidChange!(textField: self)
    }
  }
    
    
}
